package com.ts.controller;

import com.alibaba.fastjson.JSONObject;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import com.ts.base.BaseController;
import com.ts.entity.MonitorEntity;
import com.ts.util.FileUtil;
import com.ts.util.PageData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.io.*;

@RestController
@Slf4j
public class FileTransferController extends BaseController {

    /**
     * 上位机给下位机传文件
     * @param info 传输内容
     * @return
     */
    @PostMapping("/upperToLower")
    public String upperToLower(@RequestBody String info){

        MonitorEntity upperMonitor = JSONObject.parseObject(info, MonitorEntity.class);
        String content = upperMonitor.getContent();
        String cutFolder = upperMonitor.getAbsLowerFolderPath();
        String fileName = upperMonitor.getSplitFileName();

        byte[] decode = Base64.decode(content);
        FileOutputStream out = null;
        try {
            File foler = new File(cutFolder);
            if(!foler.exists()){
                foler.mkdirs();
            }
            out = new FileOutputStream(foler + File.separator + fileName);
            out.write(decode);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("文件夹不存在，请先创建文件夹");
        }
        return "ok";
    }

    @GetMapping("/merge")
    public String sequence(){
        PageData pd = this.getPageData();
        String transferEntityInfo = pd.getString("transferEntityInfo");
        MonitorEntity transferEntity = JSONObject.parseObject(transferEntityInfo, MonitorEntity.class);
        FileUtil.merge(transferEntity);
        return "ok";
    }

    /**
     *
     * @return
     */
    @GetMapping("/split")
    public int splitCount(){
        PageData pd = this.getPageData();
        MonitorEntity monitorEntity = JSONObject.parseObject(pd.getString("upperMonitorInfo"), MonitorEntity.class);
        String lowerMonitorFolder = monitorEntity.getAbsLowerFolderPath();
        String fileName = monitorEntity.getLowerSendUpperFileName();
        int count = 0;
        File folder = new File(lowerMonitorFolder);
        if(!folder.exists()){
            folder.mkdirs();
        }
        File file = new File(folder + File.separator + fileName);
        count = FileUtil.getSplitFile(file, monitorEntity.getSize(), lowerMonitorFolder+"\\download");
        return count;
    }

    @RequestMapping("/lowerToUpper/{index}")
    public String  lowerToUpper(@PathVariable("index") Integer index){
        PageData pageData = this.getPageData();
        MonitorEntity upperMonitor = JSONObject.parseObject(pageData.getString("upperMonitorInfo"),MonitorEntity.class);
        String result = "";
        File folder = new File(upperMonitor.getAbsLowerFolderPath()+"\\download");
        if(folder.exists()&&folder.isDirectory()){
            String splitFileName = upperMonitor.getLowerSendUpperFileName().split("\\.")[0] + "_" + index + ".tmp";
            File splitFile = new File(upperMonitor.getAbsLowerFolderPath()+"\\download" + File.separator + splitFileName);
            if(splitFile.exists()){
                InputStream inputStream = null;
                try {
                    inputStream = new FileInputStream(splitFile);
                    byte[] bytes = new byte[(int) splitFile.length()];
                    int offset = 0;
                    int numRead = 0;
                    while (offset < bytes.length&& (numRead = inputStream.read(bytes, offset, bytes.length - offset)) >= 0) {
                        offset += numRead;
                    }
                    inputStream.close();
                    result  = Base64.encode(bytes);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}
